import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:get/get.dart';
import 'package:syncfusion_flutter_core/theme.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';

import '../controllers/home_controller.dart';

class HomeView extends GetView<HomeController> {
  const HomeView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('HomeView'),
        centerTitle: true,
      ),
      body: Center(
        // child: _pdf1(),
        // child: SfPdfViewer.asset(
        //     'assets/111.pdf'),
        child: Obx(() {
          if (controller.pdfPath.value.isEmpty) {
            return Container();
          }
          if (controller.bytes.value.isEmpty) {
            return Container();
          }

          // return SfPdfViewer.memory(controller.bytes.value,);
          return HomePage();

          // 暗黑模式的代码先注释
          // return ColorFiltered(
          //   colorFilter: ColorFilter.mode(
          //     Colors.white,
          //     // BlendMode.difference创建反转颜色。BlendMode.darken创建类似于蓝色滤镜的重叠颜色。
          //     BlendMode.difference,
          //   ),
          //   child: SfPdfViewer.memory(controller.bytes.value,),
          // );
          // return SfPdfViewer.file(File(controller.pdfPath.value));
        }),
      ),
    );
  }

  Widget _pdf1() {
    return Container(
      color: Colors.red,
      width: 1000,
      // child: SfPdfViewer.asset(
      //     'assets/111.pdf'),
      child: SfTheme(
        data: SfThemeData(
          brightness: Brightness.dark,
        ),
        child: SfPdfViewer.network(
          'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
          // 滚动方向
          scrollDirection: PdfScrollDirection.vertical,
          // 展示滚动的页码
          canShowScrollHead: true,
          // 展示滚动状态
          canShowScrollStatus: true,
          // 是否可以选中文案(选中后进行高亮)
          enableTextSelection: true,

          otherSearchTextHighlightColor: Colors.red,
          canShowSignaturePadDialog: false,

          interactionMode: PdfInteractionMode.selection,
          pageLayoutMode: PdfPageLayoutMode.single,

          canShowTextSelectionMenu: false,

          initialPageNumber: 5,
          initialZoomLevel: 5,
          canShowPageLoadingIndicator: false,
        ),
      ),
    );
  }

  Widget _pdf2(String path) {
    return Container();
    // return PDFView(
    //   // filePath: path,
    //   pdfData: controller.bytes.value,
    //   enableSwipe: true,
    //   swipeHorizontal: true,
    //   autoSpacing: false,
    //   pageFling: true,
    //   pageSnap: true,
    //   defaultPage: 0,
    //   fitPolicy: FitPolicy.BOTH,
    //   preventLinkNavigation: false,
    //   // if set to true the link is handled in flutter
    //   nightMode: true,
    //   onViewCreated: (controller) {},
    // );
  }
}

/// Represents Homepage for Navigation
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  OverlayEntry? _overlayEntry;
  final GlobalKey<SfPdfViewerState> _pdfViewerKey = GlobalKey();
  final PdfViewerController _pdfViewerController = PdfViewerController();

  void _showContextMenu(
      BuildContext context, PdfTextSelectionChangedDetails details) {
    final OverlayState _overlayState = Overlay.of(context)!;
    _overlayEntry = OverlayEntry(
      builder: (context) => Positioned(
        top: details.globalSelectedRegion!.center.dy - 55,
        left: details.globalSelectedRegion!.bottomLeft.dx,
        child: ElevatedButton(
          onPressed: () {
            Clipboard.setData(ClipboardData(text: "Hell"));
            _pdfViewerController.clearSelection();
          },
          child: Text('Copy', style: TextStyle(fontSize: 17)),
        ),
      ),
    );
    _overlayState.insert(_overlayEntry!);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Hekk"),
      ),
      body: SelectionArea(
        child: SfPdfViewer.asset(
          'assets/111.pdf',
          enableTextSelection: true,
          onTextSelectionChanged: (PdfTextSelectionChangedDetails details) {
            if (details.selectedText == null && _overlayEntry != null) {
              _overlayEntry!.remove();
              _overlayEntry = null;
            } else if (details.selectedText != null && _overlayEntry == null) {
              // _showContextMenu1(context, details);
              // _pdfViewerKey.currentState?.openBookmarkView();
            }
          },
          key: _pdfViewerKey,
          controller: _pdfViewerController,
          canShowTextSelectionMenu: false,
          pageLayoutMode: PdfPageLayoutMode.single,
        ),
      ),
    );
  }


  void _showContextMenu1(
      BuildContext context, PdfTextSelectionChangedDetails details) {
    const double height = 250;
    const double width = 150;
    final OverlayState overlayState = Overlay.of(context);
    final Size screenSize = MediaQuery.of(context).size;

    double top = details.globalSelectedRegion!.top >= screenSize.height / 2
        ? details.globalSelectedRegion!.top - height - 10
        : details.globalSelectedRegion!.bottom + 20;
    top = top < 0 ? 20 : top;
    top = top + height > screenSize.height
        ? screenSize.height - height - 10
        : top;

    double left = details.globalSelectedRegion!.bottomLeft.dx;
    left = left < 0 ? 10 : left;
    left =
    left + width > screenSize.width ? screenSize.width - width - 10 : left;
    _overlayEntry = OverlayEntry(
      builder: (BuildContext context) => Positioned(
        top: top,
        left: left,
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(4),
            boxShadow: const <BoxShadow>[
              BoxShadow(
                color: Colors.black26,
                blurRadius: 4,
                offset: Offset(2, 2),
              ),
            ],
          ),
          constraints:
          const BoxConstraints.tightFor(width: width, height: height),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              TextButton(
                onPressed: () {
                  if (details.selectedText != null) {
                    Clipboard.setData(
                        ClipboardData(text: details.selectedText!));
                    print('Text copied to clipboard: ${details.selectedText}');
                    _pdfViewerController.clearSelection();
                  }
                },
                child: const Text('Copy', style: TextStyle(fontSize: 15)),
              ),
              TextButton(
                onPressed: () {
                  final List<PdfTextLine>? textLines =
                  _pdfViewerKey.currentState?.getSelectedTextLines();
                  if (textLines != null && textLines.isNotEmpty) {
                    final HighlightAnnotation highlightAnnotation =
                    HighlightAnnotation(
                      textBoundsCollection: textLines,
                    );
                    _pdfViewerController.addAnnotation(highlightAnnotation);
                  }
                },
                child: const Text('Highlight', style: TextStyle(fontSize: 15)),
              ),
              TextButton(
                onPressed: () {
                  final List<PdfTextLine>? textLines =
                  _pdfViewerKey.currentState?.getSelectedTextLines();
                  if (textLines != null && textLines.isNotEmpty) {
                    final UnderlineAnnotation underLineAnnotation =
                    UnderlineAnnotation(
                      textBoundsCollection: textLines,
                    );
                    _pdfViewerController.addAnnotation(underLineAnnotation);
                  }
                },
                child: const Text('Underline', style: TextStyle(fontSize: 15)),
              ),
              TextButton(
                onPressed: () {
                  final List<PdfTextLine>? textLines =
                  _pdfViewerKey.currentState?.getSelectedTextLines();
                  if (textLines != null && textLines.isNotEmpty) {
                    final StrikethroughAnnotation strikethroughAnnotation =
                    StrikethroughAnnotation(
                      textBoundsCollection: textLines,
                    );
                    _pdfViewerController.addAnnotation(strikethroughAnnotation);
                  }
                },
                child:
                const Text('Strikethrough', style: TextStyle(fontSize: 15)),
              ),
              TextButton(
                onPressed: () {
                  final List<PdfTextLine>? textLines =
                  _pdfViewerKey.currentState?.getSelectedTextLines();
                  if (textLines != null && textLines.isNotEmpty) {
                    final SquigglyAnnotation squigglyAnnotation =
                    SquigglyAnnotation(
                      textBoundsCollection: textLines,
                    );
                    _pdfViewerController.addAnnotation(squigglyAnnotation);
                  }
                },
                child: const Text('Squiggly', style: TextStyle(fontSize: 15)),
              ),
            ],
          ),
        ),
      ),
    );
    overlayState.insert(_overlayEntry!);
  }
}


